import 'package:amway_superapp_creator_plugin/analysis/zhuge_goods_recommendation.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/recommend_product_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/widget/flutter_reorderable_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';

class RecommendItem extends StatefulWidget {
  RecommendItem({
    Key key,
    @required this.data,
    @required this.isFirst,
    @required this.isLast,
    @required this.vm,
  }) : super(key: key);

  final HaowuContent data;
  final isFirst;
  final isLast;
  final RecommendProductVM vm;

  @override
  RecommendItemState createState() => new RecommendItemState();
}

class RecommendItemState extends State<RecommendItem> {
  TextEditingController _textController;

  ///如果是isFromTop,显示垃圾桶按钮，如果否，显示添加按钮
  Widget _buildProductTopInfo() {
    String widgetPath = 'picture/icon_trash_bin.png';
    Widget _rightButton = GestureDetector(
      child: Image.asset(widgetPath,
          width: ScreenUtil().setWidth(24),
          height: ScreenUtil().setWidth(24),
          package: 'amway_superapp_creator_plugin'),
      onTap: () {
        ZhugeGoodsRecommendationAnalysis.goodsReCommendaionDelGoods("好物推荐页", widget.data.product.skuCode);
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) {
              return CommTipDialog(
                content: '确认删除此好物推荐吗？',
                confirmText: "知道了",
                closeText: '取消',
                confirmCallback: () {
                  widget.vm.removeItem(widget.data);
                  ZhugeGoodsRecommendationAnalysis.goodsReCommendaionDelGoodsDialog1('好物推荐页', true);
                },
                dismissCallback: (){
                  ZhugeGoodsRecommendationAnalysis.goodsReCommendaionDelGoodsDialog1('好物推荐页', false);
                },
              );
            });
      },
    );

    String _buildTagText(List<String> tagList) {
      StringBuffer buffer = StringBuffer();
      if (tagList != null && tagList.isNotEmpty) {
        for (int i = 0; i < tagList.length; i++) {
          if (i != tagList.length - 1) {
            buffer.write(tagList.elementAt(i) + '|');
          } else {
            buffer.write(tagList.elementAt(i));
          }
        }
      }
      // if(buffer.isEmpty){
      //   buffer.write('空标|空标|空标');
      // }
      return buffer.toString();
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.network(
                  widget.data.product.picture != null
                      ? widget.data.product.picture
                      : 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603966641602&di=59dc495e8c57f2da98719f80d1d816c2&imgtype=0&src=http%3A%2F%2Fpic6.58cdn.com.cn%2Fmobile%2Fbig%2Fn_v242f9dea1883642f49bf07935db6d95ca.jpg%3Fw%3D425%26h%3D320',
                  width: ScreenUtil().setWidth(105),
                  height: ScreenUtil().setWidth(105)),
              Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: ScreenUtil().setWidth(12)),
                    height: ScreenUtil().setHeight(200),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                              widget.data.product.productName != null
                                  ? widget.data.product.productName
                                  : '安利',
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(18),
                                  fontWeight: FontWeight.bold,
                                  color: ColorsConfig.c_2c2c2c,
                                  height: 1.4)),
                          Container(
                            width: ScreenUtil().setWidth(194),
                            child: Text(_buildTagText(widget.data.product.tagList),
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(12),
                                    color: ColorsConfig.c_396E75,
                                    height: 1.66)),
                          ),
                          DefaultTextStyle(
                            style: TextStyle(
                                color: ColorUtil.fromHex('#CD0000'),
                                fontWeight: FontWeight.bold),
                            child: Padding(
                              padding:
                              EdgeInsets.only(top: ScreenUtil().setHeight(8)),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                      widget.data.product.priceData != null &&
                                          widget.data.product.priceData
                                              .currency ==
                                              "RMB"
                                          ? '¥'
                                          : "¥",
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(12))),
                                  Text(
                                    widget.data.product.priceData != null
                                        ? widget.data.product.priceData.price
                                        .toStringAsFixed(2)
                                        : '66.66',
                                    style:
                                    TextStyle(fontSize: ScreenUtil().setSp(16)),
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  )),
              _rightButton
            ],
          ),
        )
      ],
    );
  }

  Widget _buildProductInputArea() {
    return Stack(
      fit: StackFit.loose,
      children: [
        Container(
            width: double.maxFinite,
            height: ScreenUtil().setHeight(190),
            alignment: Alignment.bottomCenter,
            child: Container(
              decoration: BoxDecoration(
                //背景
                  color: shouldShowAlert2()
                      ? ColorUtil.fromHex('#CD0000').withOpacity(0.2)
                      : ColorUtil.fromHex('#F8F8F8'),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(
                      Radius.circular(ScreenUtil().setWidth(6))),
                  border: Border.all(
                      color: shouldShowAlert2()
                          ? ColorUtil.fromHex('CD0000')
                          : Colors.transparent)),
              height: ScreenUtil().setHeight(170),
              alignment: Alignment.topCenter,
              child: Container(
                  width: double.maxFinite,
                  height: ScreenUtil().setHeight(150),
                  padding: EdgeInsets.only(left: ScreenUtil().setWidth(16),right: ScreenUtil().setWidth(16)),
                  child: TextFormField(
                    cursorColor: ColorsConfig.c_2c2c2c,
                    maxLines: 100,
                    keyboardAppearance: Brightness.light,
                    textInputAction: TextInputAction.done,
                    maxLengthEnforced: false,
                    controller: _textController,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        enabledBorder: InputBorder.none,
                        errorBorder: InputBorder.none,
                        disabledBorder: InputBorder.none,
                        hintText: '输入推荐语',
                        hintStyle: TextStyle(
                            color: shouldShowAlert2()?ColorUtil.fromHex('#D12020').withOpacity(0.3):ColorsConfig.c_2c2c2c.withOpacity(0.3),
                            fontSize: ScreenUtil().setSp(16))),
                    style: TextStyle(
                        color: _getTextColor(),
                        fontSize: ScreenUtil().setSp(16),
                        height: 1.5),
                    buildCounter: _buildCounter,
                    onEditingComplete: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                    },

                  )),
            )),
        Positioned(
          left: ScreenUtil().setWidth(10),
          top:ScreenUtil().setWidth(5),
          child: Container(
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('picture/icon_myrecommend_decor_bg.png',
                        package: 'amway_superapp_creator_plugin'))),
            height: ScreenUtil().setHeight(23),
            width: ScreenUtil().setWidth(48),
            child: Center(
                child: Text('我的推荐',
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(10), color: Colors.white))),
          ),
        ),
      ],
    );
  }

  Color _getTextColor() {
    if (widget.data.isEdited && !widget.data.showLengthExceededWarning) {
      return ColorsConfig.c_2c2c2c;
    } else {
      if (widget.data.showLengthExceededWarning ||
          (widget.data.displayAudits != null &&
              widget.data.displayAudits[0] != null &&
              widget.data.displayAudits[0].status == 'UN_PASS')) {
        return ColorUtil.fromHex('#D12020');
      }
    }
    return ColorsConfig.c_2c2c2c;
  }

  bool shouldShowAlert() {
    if (widget.data.isEdited && !widget.data.showLengthExceededWarning) {
      return false;
    } else {
      if (widget.data.showEmptyNotification||widget.data.showLengthExceededWarning ||
          (widget.data.displayAudits != null &&
              widget.data.displayAudits[0] != null &&
              widget.data.displayAudits[0].status == 'UN_PASS')) {
        return true;
      }
    }
    return false;
  }

  bool shouldShowAlert2() {
    if (widget.data.isEdited && !widget.data.showLengthExceededWarning) {
      return false;
    } else {
      if (widget.data.showLengthExceededWarning||widget.data.showEmptyNotification) {
        return true;
      }
    }
    return false;
  }

  Widget _buildCounter(BuildContext context,
      {int currentLength, int maxLength, bool isFocused}) {
    if(widget.data.description!=null){
      currentLength=widget.data.description.trim().length;
    }
    if (currentLength > 70) {
      if (!widget.data.showLengthExceededWarning) {
        widget.vm.showContentLengthError(widget.data, true);
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          setState(() {});
        });
      }
    } else {
      if (widget.data.showLengthExceededWarning) {
        widget.vm.showContentLengthError(widget.data, false);
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          setState(() {});
        });
      }
    }

    String status = '';
    if (widget.data.displayAudits != null &&
        widget.data.displayAudits[0].status != null) {
      status = widget.data.displayAudits[0].status;
    }

    if ((status == 'UN_PASS' || status == 'AUDITING') &&
        !widget.data.isEdited) {
      String path = status == 'UN_PASS'
          ? 'picture/icon_recommend_unpass.png'
          : 'picture/icon_recommend_auditing.png';
      return Image.asset(
        path,
        height: ScreenUtil().setHeight(22),
        package: 'amway_superapp_creator_plugin',
      );
    }

    return Text('$currentLength/70',
        semanticsLabel: 'character count',
        style: TextStyle(
            color: shouldShowAlert2()
                ? ColorUtil.fromHex('#FF0000').withOpacity(0.2)
                : ColorsConfig.c_2c2c2c.withOpacity(0.3),
            fontSize: ScreenUtil().setSp(16)));
  }

  Widget _buildChild(BuildContext context, ReorderableItemState state) {
    BoxDecoration decoration;

    if (state == ReorderableItemState.dragProxy ||
        state == ReorderableItemState.dragProxyFinished) {
      // slightly transparent background white dragging (just like on iOS)
      decoration = BoxDecoration(color: Color(0xD0FFFFFF));
    } else {
      bool placeholder = state == ReorderableItemState.placeholder;
      decoration = BoxDecoration(color: placeholder ? null : Colors.white);
    }

    Widget content = Row(
      children: [
        Expanded(
          child: Opacity(
            opacity: state==ReorderableItemState.placeholder?0.0:1.0,
            child: Container(
              margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(16), 0,
                  ScreenUtil().setWidth(16), ScreenUtil().setHeight(12)),
              height: ScreenUtil().setHeight(344),
              decoration: new BoxDecoration(
                //背景
                  color: Colors.white,
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(
                      Radius.circular(ScreenUtil().setWidth(12))),
                  //设置四周边框
                  boxShadow: [
                    BoxShadow(
                        color: ColorUtil.fromHex('#000000').withOpacity(0.08),
                        blurRadius: ScreenUtil().setWidth(12))
                  ]),
              child: Padding(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil().setWidth(15),
                    ScreenUtil().setHeight(16),
                    ScreenUtil().setWidth(15),
                    ScreenUtil().setHeight(16)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Expanded(child: _buildProductTopInfo()),
                    _buildProductInputArea()
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );

    content = DelayedReorderableListener(
      child: content,
    );
    return Container(child: content, decoration: decoration);
  }

  @override
  Widget build(BuildContext context) {
    return ReorderableItem(
        key: widget.key, //
        childBuilder: _buildChild);
  }

  @override
  void initState() {
    _textController = TextEditingController(text: widget.data.description);
    _textController.addListener(() {
      String current = _textController.text.trim();
      if (!widget.data.isEdited&&current!=widget.data.description&&current.length>0) {
        widget.data.isEdited = true;
        widget.data.showEmptyNotification = false;
      }
      widget.data.description = current;
      widget.vm.notifyListeners();
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(RecommendItem oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }
}
